<?php

namespace app\admin\model;

use think\Model;

class ArticleModel extends Model
{
	protected $name = 'article';
	
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = true;
	
	/**
	 * 根据搜索条件获取用户列表信息
	 * @author [tegic] [i@izww.cn]
	 */
	public function getArticleByWhere($map, $Nowpage, $limits)
	{
		return $this->field('article.*,name')->join('article_cate', 'article.cate_id = article_cate.id', 'left')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
	}
	
	/**
	 * [insertArticle 添加文章]
	 * @author [tegic] [i@izww.cn]
	 */
	public function insertArticle($param)
	{
		try {
			$result = $this->allowField(true)->save($param);
			
			if (false === $result) {
				return [ 'code' => -1, 'data' => '', 'msg' => $this->getError() ];
			} else {
				$data = [
					'id'          => $this->id,
					'title'       => $this->title,
					'desc'        => $this->remark,
					'create_time' => (int)strtotime($this->create_time),
					'update_time' => (int)strtotime($this->update_time),
				];
				add_es($data);
				return [ 'code' => 1, 'data' => '', 'msg' => '文章添加成功' ];
			}
		} catch (PDOException $e) {
			return [ 'code' => -2, 'data' => '', 'msg' => $e->getMessage() ];
		}
	}
	
	/**
	 * [updateArticle 编辑文章]
	 * @author [tegic] [i@izww.cn]
	 */
	public function updateArticle($param)
	{
		try {
			$result = $this->allowField(true)->save($param, [ 'id' => $param['id'] ]);
			if (false === $result) {
				return [ 'code' => 0, 'data' => '', 'msg' => $this->getError() ];
			} else {
				$data = [
					'id'          => $this->id,
					'title'       => $this->title,
					'desc'        => $this->remark,
					'create_time' => (int)strtotime($this->create_time),
					'update_time' => (int)strtotime($this->update_time),
				];
//				halt($data);
				add_es($data);
				return [ 'code' => 1, 'data' => '', 'msg' => '文章编辑成功' ];
			}
		} catch (PDOException $e) {
			return [ 'code' => 0, 'data' => '', 'msg' => $e->getMessage() ];
		}
	}
	
	/**
	 * [getOneArticle 根据文章id获取一条信息]
	 * @author [tegic] [i@izww.cn]
	 */
	public function getOneArticle($id)
	{
		return $this->where('id', $id)->find();
	}
	
	/**
	 * [delArticle 删除文章]
	 * @author [tegic] [i@izww.cn]
	 */
	public function delArticle($id)
	{
		try {
			$this->where('id', $id)->delete();
			del_es($id);
			return [ 'code' => 1, 'data' => '', 'msg' => '文章删除成功' ];
		} catch (PDOException $e) {
			return [ 'code' => 0, 'data' => '', 'msg' => $e->getMessage() ];
		}
	}
	
}
